package com.asggo.g21.domain;

import com.asggo.g21.enums.ResultCode;
import java.io.Serializable;
import lombok.Builder;

/**
 * Created by IntelliJ IDEA.
 *
 * @author eric 2023/12/20 12:57
 */
@Builder
public record R<T extends Serializable>(String code, String msg, T body) implements Serializable {

  public static <T extends Serializable> R<T> ok() {
    return restResult(null, ResultCode.RC_SUCCESS);
  }

  public static <T extends Serializable> R<T> ok(T data) {
    return restResult(data, ResultCode.RC_SUCCESS);
  }

  public static <T extends Serializable> R<T> fail() {
    return restResult(null, ResultCode.RC_FAIL);
  }

  public static <T extends Serializable> R<T> fail(T data) {
    return restResult(data, ResultCode.RC_FAIL);
  }

  public static <T extends Serializable> R<T> fail(String code, String msg) {
    return restResult(null, code, msg);
  }

  public static <T extends Serializable> R<T> fail(ResultCode resultCode, T body) {
    return restResult(body, resultCode);
  }

  private static <T extends Serializable> R<T> restResult(T body, ResultCode resultCode) {
    return restResult(body, resultCode.getCode(), resultCode.getMessage());
  }

  private static <T extends Serializable> R<T> restResult(T data, String code, String msg) {
    return new RBuilder<T>().body(data).code(code).msg(msg).build();
  }

  public static <T extends Serializable> boolean isError(R<T> ret) {
    return !isSuccess(ret);
  }

  public static <T extends Serializable> boolean isSuccess(R<T> ret) {
    return ResultCode.RC_SUCCESS.getCode().equals(ret.code);
  }
}
